package com.example.viewpager_fragment.activity


import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.widget.ViewPager2
import com.example.viewpager_fragment.R
import com.example.viewpager_fragment.adapter.ViewPagerAdapter
import com.example.viewpager_fragment.fragment.FirstFragment
import com.example.viewpager_fragment.fragment.SecondFragment
import com.example.viewpager_fragment.fragment.ThirdFragment

class MainActivity : AppCompatActivity() {

    private lateinit var windowManager: WindowManager
    private lateinit var floatWindow: View
    private val OVERLAY_PERMISSION_REQUEST_CODE = 1001  // 权限请求码


    // 记录触摸点与悬浮窗的偏移量
    private var isDragging = false
    private var touchStartX = 0f
    private var touchStartY = 0f
    private var windowStartX = 0
    private var windowStartY = 0
    private var screenWidth = 0
    private var screenHeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 获取屏幕尺寸
        val displayMetrics = resources.displayMetrics
        screenWidth = displayMetrics.widthPixels
        screenHeight = displayMetrics.heightPixels

        // 检查并申请悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE)
        } else {
            // 已有权限，直接创建悬浮窗
            createFloatWindow()
        }

    }
    // 处理权限申请结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
                createFloatWindow() // 用户授权后创建悬浮窗
            } else {
                Toast.makeText(this, "请开启悬浮窗权限以使用功能", Toast.LENGTH_LONG).show()
            }
        }
    }
    // 创建带ViewPager2的悬浮窗
    @SuppressLint("ClickableViewAccessibility")
    private fun createFloatWindow() {
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager

        // 创建悬浮窗根布局
        val floatRoot = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setBackgroundColor(0xCCFFFFFF.toInt()) // 半透明白色背景
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
        }

        // 创建ViewPager2并添加到悬浮窗
        val viewPager = ViewPager2(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                800, // 悬浮窗宽度
                1000  // 悬浮窗高度
            )

            // 设置适配器
            adapter = ViewPagerAdapter(fragmentManager = supportFragmentManager, lifecycle = lifecycle).apply {
                addFragment(FirstFragment())
                addFragment(SecondFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
                addFragment(ThirdFragment())
            }
        }

        floatRoot.addView(viewPager)

        // 配置悬浮窗参数
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                @Suppress("DEPRECATION")
                WindowManager.LayoutParams.TYPE_PHONE
            },

            // 关键：允许触摸事件和焦点，否则无法接收触摸
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or            // 不获取焦点，避免影响其他应用
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or          // 允许底层视图接收触摸
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,        // 监听窗外触摸
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.LEFT
            x = 100  // 初始X位置
            y = 100  // 初始Y位置
        }

        // 添加悬浮窗到窗口
        floatWindow = floatRoot
        try {
            windowManager.addView(floatWindow, params)
            Toast.makeText(this, "悬浮窗创建成功", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "创建悬浮窗口失败: ${e.message}", Toast.LENGTH_LONG).show()
        }

        // 移动悬浮窗
        floatWindow.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 记录初始触摸位置
                    touchStartX = event.rawX
                    touchStartY = event.rawY
                    // 记录当前窗口位置
                    windowStartX = params.x
                    windowStartY = params.y
                    // 标记开始触摸
                    isDragging = false
                    true
                }

                MotionEvent.ACTION_MOVE -> {
                    // 计算移动距离
                    val dx = (event.rawX - touchStartX).toInt()
                    val dy = (event.rawY - touchStartY).toInt()

                    // 判断是否达到拖拽阈值（避免误触）
                    if (Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > 5) {
                        isDragging = true
                        viewPager.parent.requestDisallowInterceptTouchEvent(false)
                        // 计算新位置
                        var newX = windowStartX + dx
                        var newY = windowStartY + dy
                        Log.d("MoveX:","$newX")

                        // 限制在屏幕内
                        newX = newX.coerceAtLeast(0)
                        newY = newY.coerceAtLeast(0)
                        newX = newX.coerceAtMost(screenWidth - floatWindow.width)
                        newY = newY.coerceAtMost(screenHeight - floatWindow.height)

                        // 更新位置
                        params.x = newX
                        params.y = newY
                        windowManager.updateViewLayout(floatWindow, params)
                    }else {
                        // 横向滑动，允许ViewPager拦截事件（正常切换页面）
                        viewPager.parent.requestDisallowInterceptTouchEvent(true)
                    }
                    true
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 如果不是拖拽，可能是点击事件
                    if (!isDragging) {
                        // 这里可以处理点击事件，例如切换ViewPager页面
                        viewPager.currentItem = (viewPager.currentItem + 1) % 3
                    }
                    true
                }

                else -> false
            }
        }
    }

    // 页面销毁时移除悬浮窗（避免内存泄漏）
    override fun onDestroy() {
        super.onDestroy()
        try {
            if (::floatWindow.isInitialized) {
                windowManager.removeView(floatWindow)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}
